package liurong.driver.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池测试
 * 
 * @author liurong
 *
 * @date 2018年12月22日
 */
public class ThreadPoolExecutorTest {
	public static void main(String[] args) throws Exception {
		// int corePoolSize, 初始化线程数
		// int maximumPoolSize, 最大线程数
		// long keepAliveTime, 线程闲置时间
		// TimeUnit unit, 闲置时间单位
		// BlockingQueue<Runnable> workQueue, 程序运行队列
		// ThreadFactory threadFactory, 线程生产者
		// RejectedExecutionHandler handler 拒绝策略执行者
		ExecutorService executorService = new ThreadPoolExecutor(2, 10, 60, TimeUnit.SECONDS,
				new LinkedBlockingQueue<>(10), new RejectedExecutionHandler() {
					@Override
					public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
						// 报警由这里放出
						System.err.println("警报>>>>>>>队列已满:" + executor.getQueue().size());
					}
				});

		for (int i = 0; i < 1000; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					try {
						while (true) {
							System.out.println(Thread.currentThread().getName() + ":运行中");
							TimeUnit.SECONDS.sleep(1);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
			TimeUnit.MILLISECONDS.sleep(500);
		}
	}
}
